# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def check(root):
            if (not root.left) and (not root.right):
                return root.val, root.val
            little = root.val
            large = root.val
            if root.left:
                llittle, llarge = check(root.left)
                if llarge>=root.val: raise Exception("lalala")
                little = min(little, llittle)
                large = max(large, llarge)
            if root.right:
                rlittle, rlarge = check(root.right)
                if rlittle<=root.val: raise Exception("lalala")
                little = min(little, rlittle)
                large = max(large, rlarge)
            return little, large
        
        if not root: return True
        try:
            check(root)
        except Exception as e:
            return False
        return True

root = TreeNode(5)
root.left = TreeNode(14)
root.left.left = TreeNode(1)
print(Solution().isValidBST(root))